package cn.com.jdyun.interceptor;

import cn.com.jdyun.exception.AuthException;
import cn.com.jdyun.dto.UserCredit;
import cn.com.jdyun.pojo.User;
import cn.com.jdyun.service.UserService;
import cn.com.jdyun.util.Constant;
import cn.com.jdyun.util.reponse.Result;
import cn.com.jdyun.util.reponse.Status;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 授权认证：
 * 1，验证是否登陆，
 * 2，是否有相应权限访问（无需设置角色的，即已登录即可）
 *
 * @author Administrator
 */
public class AuthHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HandlerMethod methodHandler = (HandlerMethod) handler;
        Auth auth = methodHandler.getMethodAnnotation(Auth.class);
        // 1，auth为null,该资源访问无限制
        // 2，auth不为null,auth.value()长度为0，该资源需要登陆才能访问
        // 3，auth不为null,auth.value()长度不为0，该资源需要登陆，并且当前用户拥有相应角色方可访问
        if (auth == null) {
            return true;
        }
        HttpSession session = request.getSession(false);
        if (session == null) {
            return goback(request, response);
        }
        Object user = session.getAttribute(Constant.ACCOUNT_Mining);
        UserCredit sessionUser = (UserCredit) user;
        if(StringUtils.isEmpty(sessionUser.getId())){
            return goback(request, response);
        }
        User user1 = userService.getById(sessionUser.getId());
        if(user1.getFlag().equals(new Byte("1")) ||user1.getFlag().equals(new Byte("2"))){
            return goback(request, response);
        }
        if (user == null) {
            return goback(request, response);
        }
        if (!auth.value()) {
            return true;
        } else {
            if (sessionUser.getAdmin()) {
                return true;
            }
        }
        return goback(request, response);
    }

    private boolean goback(HttpServletRequest request, HttpServletResponse response) throws Exception {
        throw new AuthException(Result.create(Status.ACCESS_DENIED, null));
    }

}
